using System.Text;
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;

namespace BlazeApps.Library.News
{
    [Serializable()]
    public class NewsDetail : Csla.BusinessBase<NewsDetail>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _id = Guid.NewGuid();
        private string _title = string.Empty;
        private string _body = string.Empty;
        private SmartDate _createdate = new SmartDate(DateTime.Now);
        private SmartDate _expiredate = new SmartDate(DateTime.Now);
        private Boolean _Sticky = false;
        private Guid _userid = Guid.Empty;

        [System.ComponentModel.DataObjectField(true, true)]
        public Guid id
        {
            get
            {
                CanReadProperty("id", true);
                return _id;
            }
        }

        public string title
        {
            get
            {
                CanReadProperty("title", true);
                return _title;
            }
            set
            {
                CanWriteProperty("title", true);
                if (value == null)
                    value = string.Empty;
                if (!_title.Equals(value))
                {
                    _title = value;
                    PropertyHasChanged("title");
                }
            }
        }

        public string body
        {
            get
            {
                CanReadProperty("body", true);
                return _body;
            }
            set
            {
                CanWriteProperty("body", true);
                if (value == null)
                    value = string.Empty;
                if (!_body.Equals(value))
                {
                    _body = value;
                    PropertyHasChanged("body");
                }
            }
        }

        public DateTime createdate
        {
            get
            {
                CanReadProperty("createdate", true);
                return _createdate.Date;
            }
        }

        public string createdateString
        {
            get
            {
                CanReadProperty("createdate", true);
                return _createdate.Text;
            }
            set
            {
                CanWriteProperty("createdate", true);
                if (value == null)
                    value = string.Empty;
                if (!_createdate.Equals(value))
                {
                    _createdate.Text = value;
                    PropertyHasChanged("createdate");
                }
            }
        }

        public DateTime expiredate
        {
            get
            {
                CanReadProperty("expiredate", true);
                return _expiredate.Date;
            }
        }

        public string expiredateString
        {
            get
            {
                CanReadProperty("expiredate", true);
                return _expiredate.Text;
            }
            set
            {
                CanWriteProperty("expiredate", true);
                if (value == null)
                    value = string.Empty;
                if (!_expiredate.Equals(value))
                {
                    _expiredate.Text = value;
                    PropertyHasChanged("expiredate");
                }
            }
        }

        public Boolean Sticky
        {
            get
            {
                return _Sticky;
            }
            set
            {
                CanWriteProperty("Sticky", true);
                if (!_Sticky.Equals(value))
                {
                    _Sticky = value;
                    PropertyHasChanged("Sticky");
                }
            }
        }

        public Guid Userid
        {
            get
            {
                CanReadProperty("Userid", true);
                return _userid;
            }
            set
            {
                CanWriteProperty("Userid", true);
                if (!_userid.Equals(value))
                {
                    _userid = value;
                    PropertyHasChanged("Userid");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _id;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // title
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "title");
            //
            // body
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "body");
            //
            // createdate
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "createdateString");
            //
            // expiredate
            //
            //ValidationRules.AddRule(CommonRules.StringRequired, "expiredateString");
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in NewsDetail
            //AuthorizationRules.AllowRead("id", "NewsDetailReadGroup");
            //AuthorizationRules.AllowRead("title", "NewsDetailReadGroup");
            //AuthorizationRules.AllowRead("body", "NewsDetailReadGroup");
            //AuthorizationRules.AllowRead("createdate", "NewsDetailReadGroup");
            //AuthorizationRules.AllowRead("expiredate", "NewsDetailReadGroup");

            //AuthorizationRules.AllowWrite("title", "NewsDetailWriteGroup");
            //AuthorizationRules.AllowWrite("body", "NewsDetailWriteGroup");
            //AuthorizationRules.AllowWrite("createdate", "NewsDetailWriteGroup");
            //AuthorizationRules.AllowWrite("expiredate", "NewsDetailWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in NewsDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("NewsDetailViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in NewsDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("NewsDetailAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in NewsDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("NewsDetailEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in NewsDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("NewsDetailDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private NewsDetail()
        { /* require use of factory method */
        }

        public static NewsDetail NewNewsDetail()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a NewsDetail");
            return DataPortal.Create<NewsDetail>();
        }

        public static NewsDetail GetNewsDetail()
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a NewsDetail");
            return DataPortal.Fetch<NewsDetail>(new Criteria());
        }

        public static NewsDetail GetNewsDetail(Guid id)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a NewsDetail");
            return DataPortal.Fetch<NewsDetail>(new Criteria(id));
        }

        public static void DeleteNewsDetail(Guid id)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a NewsDetail");
            DataPortal.Delete(new Criteria(id));
        }

        public override NewsDetail Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a NewsDetail");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a NewsDetail");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a NewsDetail");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid id;

            public Criteria()
            {
            }

            public Criteria(Guid id)
            {
                this.id = id;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);         

            DAL.AddParameter("@newsid", criteria.id);

            using(SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetNewsByNewsID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            while (dr.Read())
            {
                _id = dr.GetGuid("newsid");
                _body = dr.GetString("body");
                _title = dr.GetString("title");
                _expiredate = dr.GetSmartDate("expiredate", _expiredate.EmptyIsMin);
                _Sticky = dr.GetBoolean("sticky");
                _userid = dr.GetGuid("userid");
            }
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }

        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertNews.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@title", _title);
            DAL.AddParameter("@body", _body);
            DAL.AddParameter("@expiredate", _expiredate.DBValue);
            DAL.AddParameter("@newsid", _id);
            DAL.AddParameter("@sticky", _Sticky);
            DAL.AddParameter("@userid", _userid);
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdateNews.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@newsid", _id);
            DAL.AddParameter("@title", _title);
            DAL.AddParameter("@body", _body);
            DAL.AddParameter("@expiredate", _expiredate.DBValue);
            DAL.AddParameter("@sticky", _Sticky);
        }

        private void UpdateChildren(SqlConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_id));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeleteNews.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@newsid", criteria.id);
        }

        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
